package com.xiaobaibai.security.master_token.config;

import com.xiaobaibai.security.handler.HttpFailureHandler;
import com.xiaobaibai.security.master_token.filter.No2JwtAuthenticationFilter;
import com.xiaobaibai.security.master_token.provider.JwtAuthenticationProvider;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutFilter;

//@Configuration
public class No2TokenConfig<T extends No2TokenConfig<T, B>, B extends HttpSecurityBuilder<B>>
        extends AbstractHttpConfigurer<T, B> {

    private No2JwtAuthenticationFilter no2JwtAuthenticationFilter;

    private JwtAuthenticationProvider jwtAuthenticationProvider;

//    private AuthenticationFailureHandler failureHandler;

    public No2TokenConfig(String excludeUri,AuthenticationFailureHandler failureHandler){
        no2JwtAuthenticationFilter=new No2JwtAuthenticationFilter(excludeUri);
        no2JwtAuthenticationFilter.setFailureHandler(failureHandler);
    }

    @Override
    public void configure(B http) throws Exception {
        no2JwtAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        no2JwtAuthenticationFilter.setAuthenticationFailureHandler(new HttpFailureHandler());

        //把此filter放入容器,然后返回放入容器后的对象,这样@PostConstruct方法才会执行(推荐多用@Component)
        No2JwtAuthenticationFilter filter =
                postProcess(this.no2JwtAuthenticationFilter);


        http.authenticationProvider(jwtAuthenticationProvider)
                .addFilterAfter(filter, LogoutFilter.class);
    }

    public No2TokenConfig<T, B> tokenSuccessHandler(AuthenticationSuccessHandler successHandler){
        no2JwtAuthenticationFilter.setAuthenticationSuccessHandler(successHandler);
        return this;
    }

    public No2TokenConfig<T, B> setJwtAuthenticationProvider(JwtAuthenticationProvider jwtAuthenticationProvider){
        this.jwtAuthenticationProvider=jwtAuthenticationProvider;
        return this;
    }

//    public No2TokenConfig<T, B> setFailureHandler(AuthenticationFailureHandler failureHandler) {
//        this.failureHandler = failureHandler;
//        return this;
//    }
}
